package components.core {
	import flash.events.MouseEvent;

	import mx.binding.utils.BindingUtils;
	import mx.collections.ArrayList;
	import mx.events.FlexEvent;

	import spark.components.Button;
	import spark.components.List;
	import spark.components.PopUpAnchor;
	import spark.components.supportClasses.SkinnableComponent;
	import spark.events.IndexChangeEvent;

	import tv.digitalretro.components.MessageBox;

	[Event(name="change", type="spark.events.IndexChangeEvent")]
	public class DropDownComponent extends SkinnableComponent {
		[SkinPart]
		public var btn_Open:Button;
		[SkinPart]
		public var listPopUp:PopUpAnchor;
		[SkinPart]
		public var list:List;

		public var labelName:String;
		public var iconName:String;

		public var buttonDefaultLabel:String;
		public var listEmptyHeader:String;
		public var listEmptyMessage:String;

		[Bindable]
		public var selectionName:String;

		private var _icon:Class;

		public function get icon():Class {
			return _icon;
		}

		[Bindable]
		public function set icon(icon:Class):void {
			_icon = icon;
		}

		[Bindable]
		public var dataProvider:ArrayList;

		private var open:Boolean;

		public function DropDownComponent() {
			super();
			addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
		}

		private function onCreationComplete(event:FlexEvent):void {
			if (labelName != null && labelName.length > 0) {
				BindingUtils.bindProperty(this, "selectionName", list, [ "selectedItem", labelName ]);
			}

			if (iconName != null && iconName.length > 0) {
				BindingUtils.bindProperty(this, "icon", list, [ "selectedItem", iconName ]);
			}
		}

		public function set selectedItem(value:Object):void {
			list.selectedItem = value;
			if (value) {
				selectionName = value[labelName];
				icon = value[iconName];
			}
		}

		protected override function partAdded(partName:String, instance:Object):void {
			super.partAdded(partName, instance);

			if (instance == btn_Open) {
				btn_Open.addEventListener(MouseEvent.CLICK, onClick);
				btn_Open.label = buttonDefaultLabel;
			}
			if (instance == list) {
				list.labelField = labelName;
				list.addEventListener(IndexChangeEvent.CHANGE, onChange);
			}
		}

		private function openCloseList(open:Boolean):void {
			listPopUp.displayPopUp = this.open = open;
		}

		private function onChange(event:IndexChangeEvent):void {
			openCloseList(false);
			dispatchEvent(event);
		}

		private function onClick(event:MouseEvent):void {
			if (open) {
				openCloseList(false);
			} else {
				if (dataProvider != null && dataProvider.length > 0) {
					openCloseList(true);
				} else {
					MessageBox.show(MessageBox.MB_OK, MessageBox.IC_INFO, listEmptyHeader, listEmptyMessage);
				}
			}
		}
	}
}